const axios = require('axios');

class MySQLMCPClient {
  constructor(baseUrl = 'http://localhost:8099') {
    this.baseUrl = baseUrl;
    this.requestId = 0;
  }

  async callTool(name, args = {}) {
    const request = {
      jsonrpc: "2.0",
      id: (++this.requestId).toString(),
      method: "tools/call",
      params: {
        name,
        arguments: args
      }
    };

    try {
      console.log(`调用工具: ${name}`);
      console.log('请求:', JSON.stringify(request, null, 2));
      
      const response = await axios.post(`${this.baseUrl}/mcp/call`, request);
      
      console.log('响应:', JSON.stringify(response.data, null, 2));
      return response.data.result;
    } catch (error) {
      console.error(`MCP调用失败: ${error.message}`);
      if (error.response) {
        console.error('错误响应:', error.response.data);
      }
      throw error;
    }
  }

  // 便捷方法
  async query(sql, params = []) {
    return this.callTool('query', { sql, params });
  }

  async execute(sql, params = []) {
    return this.callTool('execute', { sql, params });
  }

  async listTables() {
    return this.callTool('list_tables');
  }

  async describeTable(tableName) {
    return this.callTool('describe_table', { table: tableName });
  }

  async testConnection() {
    return this.callTool('test_connection');
  }
}

// 测试函数
async function testMCPService() {
  const client = new MySQLMCPClient();
  
  console.log('=== MySQL MCP 服务测试 ===\n');
  
  try {
    // 1. 测试连接
    console.log('1. 测试数据库连接...');
    const connectionStatus = await client.testConnection();
    console.log('✅ 连接状态:', connectionStatus);
    console.log('');
    
    // 2. 获取表列表
    console.log('2. 获取数据库表列表...');
    const tables = await client.listTables();
    console.log('✅ 数据库表:', tables);
    console.log('');
    
    // 3. 如果有表，获取第一个表的结构
    if (tables.tables && tables.tables.length > 0) {
      const firstTable = tables.tables[0];
      console.log(`3. 获取表结构: ${firstTable}...`);
      const tableStructure = await client.describeTable(firstTable);
      console.log('✅ 表结构:', tableStructure);
      console.log('');
      
      // 4. 查询该表的数据
      console.log(`4. 查询表数据: ${firstTable}...`);
      const queryResult = await client.query(`SELECT * FROM ${firstTable} LIMIT 5`);
      console.log('✅ 查询结果:', queryResult);
      console.log('');
    }
    
    // 5. 测试简单查询
    console.log('5. 测试简单查询...');
    const simpleQuery = await client.query('SELECT 1 as test_value, NOW() as current_time');
    console.log('✅ 简单查询结果:', simpleQuery);
    console.log('');
    
    console.log('🎉 所有测试通过！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    process.exit(1);
  }
}

// 健康检查函数
async function healthCheck() {
  try {
    console.log('=== 健康检查 ===');
    const response = await axios.get('http://localhost:8099/health');
    console.log('✅ 服务状态:', response.data);
    
    const dbResponse = await axios.get('http://localhost:8099/health/database');
    console.log('✅ 数据库状态:', dbResponse.data);
    
  } catch (error) {
    console.error('❌ 健康检查失败:', error.message);
  }
}

// 主函数
async function main() {
  const args = process.argv.slice(2);
  
  if (args.includes('--health')) {
    await healthCheck();
  } else {
    await testMCPService();
  }
}

// 运行测试
if (require.main === module) {
  main().catch(console.error);
}

module.exports = MySQLMCPClient; 